package com.omesoft.hksnore.me;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.omesoft.hksnore.R;
import com.omesoft.hksnore.util.CustomToast;
import com.omesoft.hksnore.util.StringUtill;
import com.omesoft.hksnore.util.dao.FamilyIfc;
import com.omesoft.hksnore.util.dao.FamilyIfcImpl;
import com.omesoft.hksnore.util.data.MySharedPreferencesUtil;
import com.omesoft.hksnore.util.dialog.MyProgressBarDialogUtil;
import com.omesoft.hksnore.util.entity.FamilyDTO;
import com.omesoft.hksnore.util.json.ReErrorCode;
import com.omesoft.hksnore.util.json.SnorekillerJsonUtil;
import com.omesoft.hksnore.util.myactivity.MyActivity;
import com.omesoft.hksnore.util.omeview.OvalHollowImageView;
import com.omesoft.hksnore.util.photo.MyBitmapUtil;
import com.omesoft.hksnore.util.photo.MyFileUtils;
import com.omesoft.hksnore.util.photo.MyPicUtils;
import com.omesoft.hksnore.util.photo.MyPixelConvertUtil;
import com.omesoft.hksnore.util.photo.SettingUtil;
import com.omesoft.hksnore.util.titlebar.MyTitlebarUtil;
import com.omesoft.hksnore.util.web.CheckNetwork;
import com.omesoft.hksnore.util.web.DataCheckUtil;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * Created by Omesoft on 2017/2/23.
 */

public class ProfileAvtivity extends MyActivity implements View.OnClickListener {
    private LinearLayout mSetHeadPic_ll;
    private LinearLayout mSetNiciName_ll;
    private OvalHollowImageView mHeadPid_iv;
    private TextView mNickName_tv;
    private String fileName = "";
    private Bitmap bitmap,mNewBitmap;
    private static final String TAG = "ProfileAvtivity";

    private boolean pic_Flag = false;
    private FamilyIfc ifc;
    private FamilyDTO family;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.snore_activity_profile);
        initTitleBar();
        initView();
        initHandler();
    }

    @Override
    protected void initTitleBar() {
        super.initTitleBar();
        MyTitlebarUtil.showTitleName(activity, R.string.me_profile);
        MyTitlebarUtil.showIbLeft(activity, R.mipmap.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        try {
            ifc = new FamilyIfcImpl(context);
            family = ifc.findFamily();
            Log.e("xx","heheh "+family.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 头像设置窗口
     */

    private void getPicDialog() {
        final Dialog changeAvatarDialog = new Dialog(context, R.style.myDialog);
        View v = LayoutInflater.from(ProfileAvtivity.this).inflate(R.layout.my_dialog_change_avater, null);
        Button takePhoto = (Button) v.findViewById(R.id.changeAvatarDialog_takePhoto);
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fileName = getFileName() + ".jpg";

                MyBitmapUtil.showPicFromCamera(ProfileAvtivity.this, fileName);

                changeAvatarDialog.dismiss();
            }
        });
        Button album = (Button) v.findViewById(R.id.changeAvatarDialog_album);
        album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fileName = getFileName() + ".jpg";

                MyBitmapUtil.showPicFromPhotoAlbum(ProfileAvtivity.this);
                changeAvatarDialog.dismiss();
            }
        });

        changeAvatarDialog.setContentView(v);
        changeAvatarDialog.show();

    }

    private String getFileName() {
        return "snorekiller" + "_" + StringUtill.getTimeName();
    }

    @Override
    protected void initView() {
        super.initView();
        mSetHeadPic_ll = (LinearLayout) findViewById(R.id.profile_ll_head_pic);
        mSetHeadPic_ll.setOnClickListener(this);
        mSetNiciName_ll = (LinearLayout) findViewById(R.id.profile_ll_nickname);
        mSetNiciName_ll.setOnClickListener(this);
        mNickName_tv = (TextView) findViewById(R.id.profile_tv_nickname);
        if (family.getName() != null){

            mNickName_tv.setText(family.getName());
        }
        mHeadPid_iv = (OvalHollowImageView) findViewById(R.id.profile_iv_head_pictrue);
        Intent intent = getIntent();

        if (intent != null  ){
            bitmap =intent.getParcelableExtra("bitmap");
            mHeadPid_iv.setImageBitmap(bitmap);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Uri uri = MyBitmapUtil.getPicUriCallBack(requestCode, resultCode, intent);

        switch (requestCode) {
            case MyBitmapUtil.PIC_FROM_CAMERA:
                switch (resultCode) {
                    case 0:
                        bitmap = null;
                        Log.e(TAG, "执行第一步");
                        break;
                    case -1:
                        if (!DataCheckUtil.isNull(fileName)) {
                            File file = new File(MyBitmapUtil.PHOTO_DIR, fileName);

                                MyPicUtils.showPicToCutPhoto(Uri.fromFile(file), ProfileAvtivity.this);

                            Log.e(TAG, "执行第二步");
                            pic_Flag = true;
                        }
                        Log.e(TAG, "执行第三步");

                }
                break;
            case MyBitmapUtil.PIC_FROM_PHOTOALBUM:
                System.out.println("requestCode::BitmapUtil.PIC_FROM_PHOTOALBUM");
                if (uri != null) {
                    Log.e(TAG, "执行第4步");
                    String selectedImagePath = MyBitmapUtil.getPath(uri, ProfileAvtivity.this);
                    File sourceFile = new File(selectedImagePath);
                    String[] demandFileTypes = {"jpg", "png", "gif", "tif", "bmp", "jpeg"};
                    boolean isFitFileType = MyFileUtils.isFitFileType(demandFileTypes, sourceFile);
                    if (isFitFileType) {

                            MyPicUtils.showPicToCutPhoto(Uri.fromFile(sourceFile), ProfileAvtivity.this);

                    } else {
                        CustomToast.showToasts(context, R.string.me_profilr_management_no_show_drawable);
                    }
                    pic_Flag = true;

                }
                Log.e(TAG, "执行第5步");
                break;

            case MyBitmapUtil.PIC_FROM_CUTPHOTO:
                System.out.println("requestCode::BitmapUtil.PIC_FROM_CUTPHOTO");
                if (intent != null) {
                    Bundle extras = intent.getExtras();

                    Log.e(TAG, "执行第6步  ");
                    if (extras != null) {
                        int zoomSacle = SettingUtil.getPicSaveSize(ProfileAvtivity.this);
                        System.out.println(fileName);
                        File sourceFile = new File(MyBitmapUtil.PHOTO_DIR, fileName);
                        try {
                            // 当图片大小大于512kb至少缩小两倍
                            if (sourceFile.length() / 1024 > 512) {
                                zoomSacle = zoomSacle * 10;
                            }
                            MyPicUtils.showCutPhoto(intent, zoomSacle, sourceFile.getPath());
                            if (isShowFilePic(sourceFile)) {

                                Log.e(TAG, "执行第7步");
                                pic_Flag = true;

                            }

                        } catch (FileNotFoundException e) {
                            System.out.println(e.toString());
                            Log.e(TAG, "执行第8步");
                            pic_Flag = false;

                            CustomToast.showToasts(context, R.string.error);
                        }
                    }

                }
                break;
        }
    }

    /**
     * 是否显示到图片
     */
    public boolean isShowFilePic(File file) {
        boolean exists = file.exists();
        if (exists) {
            int zoomSacle = MyPicUtils.getZoomSacleByHeightAndWidth(file.getPath(), MyPixelConvertUtil.dip2px(ProfileAvtivity.this, 73),
                    MyPixelConvertUtil.dip2px(ProfileAvtivity.this, 73));
            try {
                bitmap = MyPicUtils.getBitmapByZoomSacle(file.getPath(), zoomSacle);
                SnorekillerJsonUtil.UploadPhoto(handler,context,fileName,bitmap,family);


            } catch (Exception e) {
                e.printStackTrace();
            }

            mHeadPid_iv.setImageBitmap(bitmap);
            mHeadPid_iv.setBackgroundResource(R.color.transparent);
        }
        return exists;
    }

    @Override
    protected void initHandler() {
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case ReErrorCode.ERRCODE_SUCEED:
                        MyProgressBarDialogUtil.dismiss2Msg(R.string.me_profilr_upload_photo_succed);
                        break;
                    case ReErrorCode.ERRCODE_FAIL:
                        MyProgressBarDialogUtil.dismiss2Msg(R.string.me_profilr_upload_photo_fail);
                        CustomToast.showToasts(context,(String)msg.obj);
                        break;
                    case ReErrorCode.ERRCODE_NO_RETRUN_ERROR:
                        MyProgressBarDialogUtil.dismiss2Msg(R.string.me_profilr_upload_photo_fail);
                        break;
                }
            }
        };
    }


    /**
     * 修改昵称
     */
    private void showChangeNameDialog() {
        final Dialog updateNameDialog = new Dialog(context, R.style.myDialog2);
        View v = LayoutInflater.from(ProfileAvtivity.this).inflate(
                R.layout.dialog_updatename, null);
        Button takePhoto = (Button) v.findViewById(R.id.name_save);
        final EditText t_name = (EditText) v.findViewById(R.id.name_text);
        takePhoto.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String text = t_name.getText().toString();

                if (text.length() > 0) {
                    if (!DataCheckUtil.StringFilter(text)) {
                        if (text != null && !text.equals("")) {
                            if (CheckNetwork.checkNetwork3(context)){
                                updateNameDialog.dismiss();

                                mNickName_tv.setText(text);
                                SnorekillerJsonUtil.SetMemberInfo(handler,context,text, MySharedPreferencesUtil.getPhotoUrl(context));
                            }
                        }
                    } else {
                        CustomToast.showToastsByStr(context,
                                getString(R.string.me_profilr_updatename_tip_1));
                    }
                } else {

                    CustomToast.showToastsByStr(context,
                            getString(R.string.me_profilr_management_add_tip_1));
                }

            }
        });
        updateNameDialog.setContentView(v);
        updateNameDialog.show();
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.profile_ll_head_pic:
                getPicDialog();
                break;
            case R.id.profile_ll_nickname:
                showChangeNameDialog();
                break;
        }

    }
}
